<template>
  <div class="seckillall">
    <div class="head">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="课程名称" prop="courseName">
          <el-input
            v-model="queryParams.courseName"
            placeholder="请输入课程名称"
            clearable
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item label="课程状态" prop="courseStatus">
          <el-select
            v-model="queryParams.courseStatus"
            placeholder="请选择课程状态"
            filterable
          >
            <el-option label="启用" value="0"></el-option>
            <el-option label="禁用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="线上/线下" prop="courseType">
          <el-select
            v-model="queryParams.courseType"
            placeholder="线上/线下"
            filterable
          >
            <el-option label="线上" value="线上"></el-option>
            <el-option label="线下" value="线下"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="老师名称" prop="teacherId">
          <el-select
            v-model="queryParams.teacherId"
            placeholder="请选择教师"
            filterable
          >
            <el-option
              v-for="item in teacherList"
              :label="item.teacherName"
              :key="item.teacherId"
              :value="item.teacherId"
            ></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item label="课程栏目" prop="categoryId">
          <el-select
            v-model="queryParams.categoryId"
            placeholder="请选择课程栏目"
            filterable
          >
            <el-option
              v-for="item in categoryList"
              :label="item.categoryName"
              :key="item.categoryId"
              :value="item.categoryId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="default" @click="searchBtn()"
            >搜索</el-button
          >
          <el-button size="default" @click="resetBtn">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="middle">
        <div class="add" style="margin-left: 20px">
          <div class="button">
            <el-button type="primary" :icon="Plus" @click="handleAdd()" plain
              >新增</el-button
            >
          </div>
        </div>
        <div class="add">
          <div class="button">
            <el-button
              type="success"
              :icon="Edit"
              @click="handleEdit()"
              :disabled="single"
              plain
              >修改</el-button
            >
          </div>
        </div>
        <div class="add">
          <div class="button">
            <el-button
              type="danger"
              :icon="Delete"
              @click="handleDelete()"
              :disabled="multiple"
              plain
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
      <div class="end">
        <el-table
          :data="tableData"
          row-key="courseId"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" />
          <el-table-column label="序号" prop="index">
            <template #default="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column property="courseName" label="课程名称" />
          <el-table-column property="courseType" label="线上/线下" />
          <el-table-column property="categoryName" label="课程栏目" />
          <el-table-column property="hours" label="总学时" />
          <el-table-column property="price" label="课程价格" />
          <el-table-column property="courseStock" label="课程库存" />
          <!-- <el-table-column property="teacherName" label="老师名称" /> -->
          <el-table-column property="startTime" label="开始时间" />
          <el-table-column property="endTime" label="结束时间" />
          <el-table-column property="createTime" label="创建时间" :formatter="formatDate"/>
          <el-table-column property="updateTime" label="更新时间" :formatter="formatDate"/>
          <el-table-column label="封面图片">
  <template #default="scope">
    <img :src="scope.row.url" style="width: 50px; height: 50px" />
  </template>
</el-table-column>
          <!-- <el-table-column property="courseDescription" label="课程描述" /> -->
          <el-table-column label="状态">
            <template #default="scope">
              <!-- {{ scope.row.courseStatus }} -->
              <el-button type="success" v-if="scope.row.courseStatus == 0" plain @click="handleStatus(scope.row)"
                >正常</el-button
              >
              <el-button type="danger" v-if="scope.row.courseStatus == 1" plain @click="handleStatus(scope.row)">禁用</el-button>
              <!-- <el-button type="warning" v-if="scope.row.courseStatus == 2" plain>审核中</el-button> -->
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="small"
               @click="handleEdit(scope.row)">
                修改
              </el-button>
              <br />
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-left: 600px">
          <div class="demo-pagination-block">
            <el-pagination
              v-model:current-page="queryParams.pageNum"
              v-model:page-size="queryParams.pageSize"
              :page-sizes="[1, 2, 20, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>

      <el-dialog v-model="dialogVisible" :modal="true" width="800px">
        <el-form :model="formData" :rules="rules" ref="categoryForm">
          <el-row>
            <el-col :span="11">
              <el-form-item
                label="课程名称"
                label-width="120px"
                prop="courseName"
              >
                <el-input
                  v-model="formData.courseName"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item
                label="课程库存"
                label-width="120px"
                prop="courseStock"
              >
                <el-input
                  v-model="formData.courseStock"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item
                label="课程价格"
                label-width="120px"
                prop="coursePrice"
              >
                <el-input
                  v-model="formData.price"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="线上/线下" 
              prop="courseType" 
              label-width="120px"
               >
          <el-select
            v-model="formData.courseType"
            placeholder="线上/线下"
            filterable
          >
            <el-option label="线上" value="线上"></el-option>
            <el-option label="线下" value="线下"></el-option>
          </el-select>
        </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11">
              <el-form-item
                label="开始时间"
                label-width="120px"
                prop="startTime"
              >
                <div class="block">
                  <el-date-picker
                    v-model="formData.startTime"
                    type="date"
                    value-format="YYYY-MM-DD HH:mm"
                    format="YYYY-MM-DD HH:mm"
                    placeholder="选择日期"
                  >
                  </el-date-picker>
                </div>
              </el-form-item>
            </el-col>
           <el-col :span="11">
              <el-form-item
                label="结束时间"
                label-width="120px"
                prop="endTime"
              >
                <div class="block">
                  <el-date-picker
                    v-model="formData.endTime"
                    type="date"
                    value-format="YYYY-MM-DD HH:mm"
                    format="YYYY-MM-DD HH:mm"
                    placeholder="选择日期"
                  >
                  </el-date-picker>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
          <el-col :span="11">
                        <el-form-item label="课程栏目" label-width="120px" prop="categoryId">
                            <el-select v-model="formData.categoryId" placeholder="请选择课程栏目" label-width="120"
                               filterable >
                                <el-option v-for="item in categoryList" :label="item.categoryName"
                                    :key="item.categoryId" :value="item.categoryId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
            <el-col :span="11">
              <el-form-item
                label="课程学时"
                label-width="120px"
                prop="hours"
              >
                <el-input
                  v-model="formData.hours"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
            </el-row>
          <el-row>
  <el-col :span="22">
    <el-form-item label="封面图片" prop="url" label-width="120px">
      <input type="file" @change="handleFileChange" />
      <button @click="submitUpload" >上传</button>
      <!-- 显示上传后的图片预览 -->
      <div v-if="formData.url" style="margin-top: 10px">
        <div>图片预览：</div>
        <img :src="formData.url" style="max-width: 100px; max-height: 100px; margin-top: 10px" />
      </div>
    </el-form-item>
  </el-col>
</el-row>

          <el-row>
            <el-col :span="22">
              <el-form-item
                label="课程备注"
                label-width="120px"
                prop="courseDescription"
              >
                <el-input
                  v-model="formData.courseDescription"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleCanle">取消</el-button>
            <el-button type="primary" @click="handleConfirm"> 确认 </el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog v-model="deleteDialog" title="Tips" width="500">
        <span>确认要删除吗？</span>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="deleteDialog = false">取消</el-button>
            <el-button type="primary" @click="deleteConfirm"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>

      <el-dialog v-model="statusDialog" title="Tips" width="500">
        <span>确认要修改状态吗？</span>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="statusDialog = false">取消</el-button>
            <el-button type="primary" @click="StatusChange"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { Calendar, Search, Edit, Plus, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import dayjs from 'dayjs';
import {
  selectAllCourse,
//   selectAllTeacher,
      selectAllCategory,
      upload,
  addCourse,
  getCourse,
  updateCourse,
  updateCourseStatus,
  deleteCourse,
} from "@/api/realCourse";

//选择框
// const selectable = ref();
const categoryForm = ref(null);
const single = ref(true);
const multiple = ref(true);
const total = ref(10);
const dialogVisible = ref(false);
const data2 = ref({});//修改状态

const selected = ref("add");
//是否禁用表单
const disabled = ref(false);
const selectRow = ref([]);
const statusDialog = ref(false);
const deleteDialog = ref(false);
const deleteRow = ref([]);
const teacherList = ref([]);
const categoryList = ref([]);
const selectedFile = ref(null);


function handleFileChange(event) {
  selectedFile.value = event.target.files[0];
}

onMounted(async () => {
  await getCategoryList();
  // await selectAllCategory();
  await getCourseList();
});
//查询参数
const queryParams = ref({
  courseName: "",
  courseStatus: "",
  courseType: "",
  categoryName: "",
  pageNum: 1,
  pageSize: 5,
  campusId: 1,
//   teacherId: "",
});
// 表单参数
var formData = ref({
  courseId: "",
  courseName: "",
  categoryId: "", //栏目id
  hours: "", //课时
  price: "",
  startTime: "",
  endTime: "",
  courseStatus: "",
  teacherId: "",
  courseStock: "", //课程库存
  price: "",
  courseDescription: "", //课程描述
  createTime: "",
  updateTime: "",
  fileId: "", //图片id
  // courseTime: 1,
});
//表格参数
const tableData = ref([]);
//日期格式
const formatDate = (row, column, cellValue) => {
  return cellValue ? dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss') : '-';
};

//校验规则
const rules = {
  courseName: [
        { required: true, message: '课程名称不能为空', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在2-50个字符之间', trigger: 'blur' }
      ],
      courseStock: [
        { required: true, message: '课程库存不能为空', trigger: 'blur' },
        { pattern: /^[0-9]\d*$/, message: '库存必须是整数', trigger: 'blur' }
      ],
      price: [
        { required: true, message: '课程价格不能为空', trigger: 'blur' },
        { pattern: /^(0|[1-9]\d*)(\.\d{1,2})?$/, message: '请输入有效金额（整数或小数）', trigger: 'blur' }
      ],
      courseType: [
        { required: true, message: '请选择线上/线下', trigger: 'change' }
      ],
      startTime: [
        { required: true, message: '请选择开始时间', trigger: 'change' }
      ],
      endTime: [
        { required: true, message: '请选择结束时间', trigger: 'change' }
      ],
      hours: [
        { required: true, message: '课程学时不能为空', trigger: 'blur' },
        { pattern: /^[1-9]\d*$/, message: '学时必须是大于0的整数', trigger: 'blur' }
      ],
    
  courseStart: [
    { required: true, message: "请选择开始时间", trigger: "change" },
  ],
  courseTime: [
    {
      type: "number",
      min: 1,
      max: 72,
      message: "持续时间需在1-72周之间",
      trigger: "blur",
    },
  ],
  imagePath: [
    { required: true, message: "请输入图片路径", trigger: "blur" },
    {
      pattern: /\.(jpg|jpeg|png|gif|webp)$/,
      message: "请输入有效的图片文件路径",
      trigger: "blur",
    },
  ],
};

async function submitUpload() {
  if (!selectedFile.value) {
    alert('请先选择文件');
    return;
  }

  const formData1 = new FormData();
  formData1.append('file', selectedFile.value);

  try {
    // const response2 = await test();
    const response = await upload(formData1);

    console.log('上传成功:', response.data);
    formData.value.url = response.data.file.url;
    formData.value.fileId = response.data.file.id;
 
  } catch (error) {
    console.error('上传失败:', error);
  }
}
// 修改
function handleEdit(row) {
  resetForm();
  if (row == null) {
    row = selectRow.value[0];
  }
  console.log(row, 123);
  disabled.value = true;
  selected.value = "edit";
  const data = {
    courseId: row.courseId,
  };
  
  getCourse(data).then((res) => {
    formData.value = res.data.getCourse[0];
    dialogVisible.value = true;
  });
}
// 删除
function handleDelete(row) {
  if (row == null) {
    row = selectRow.value.map((item) => {
      return item.courseId;
    });
  } else {
    console.log(row,7328562378);
    row = [row.courseId];
  }
  deleteRow.value = row;
  deleteDialog.value = true;
}
//删除确定
function deleteConfirm() {
  console.log(deleteRow.value, 123);

  deleteCourse(deleteRow.value).then((res) => {
    if (res.code === 500) {
      ElMessage.error(res.message);
    } else {
      ElMessage.success("删除成功");
    }
    getCourseList();
  });
  deleteDialog.value = false;
}

// 修改状态
function handleStatus(row) {
  let status1;
  if (row.courseStatus == 1) {
    status1 = 0;  
  } else if (row.courseStatus == 0) {
    status1 = 1;
  };
  const data = {
    courseId: row.courseId,
    courseStatus: status1,
  };
  console.log(data,65756);
  data2.value = data;
  statusDialog.value = true;
}
//确定修改状态
function StatusChange() {
  console.log(data2,99999);
  updateCourseStatus(data2.value).then((res) => {
    if (res.code === 500) {
      ElMessage.error(res.message);
    } else {
      ElMessage.success("修改成功");
    }
    getCourseList();
  });
  statusDialog.value = false;
}

//新增
function handleAdd() {
  dialogVisible.value = true;
  selected.value = "add";
  resetForm();
}
//每页条数变换
function handleSizeChange(val) {
  console.log("每页" + val + "条");
  queryParams.value.pageSize = val;
  queryParams.value.pageNum = 1;
  getCourseList();
}
//每码变换
function handleCurrentChange(val) {
  console.log("第" + val + "页");
  queryParams.value.pageNum = val;
  getCourseList();
}

//关闭dialog
function handleCanle() {
  dialogVisible.value = false;
  // 重置表单字段
  categoryForm.value.resetFields();

  // 清除表单验证
  categoryForm.value.clearValidate();
}

// 选中某一列
function handleSelectionChange(selected) {
  console.log(selected, selected.length);
  single.value = selected.length != 1;
  multiple.value = selected.length == 0;
  selectRow.value = selected;
}

function handleConfirm() {
  // 验证表单 xxx
  categoryForm.value.validate((valid) => {
    // 重置表单字段
    // categoryForm.value.resetFields();
    if (valid) {
      // 表单验证通过，执行提交操作
      if (selected.value === "add") {
        console.log(formData.value, 99);
        addCourse(formData.value).then((res) => {
          console.log(res);
          if (res.code === 500) {
            ElMessage.error(res.message);
          } else {
            ElMessage.success("新增成功");
          }
          getCourseList();
          dialogVisible.value = false;
        });
      } else {
        updateCourse(formData.value).then((res) => {
          console.log(res);
          if (res.code === 500) {
            ElMessage.error(res.message);
          } else {
            ElMessage.success("修改成功");
          }
          getCourseList();
          dialogVisible.value = false;
        });
      }
    } else {
      // 表单验证失败，显示错误信息
      ElMessage.warning("请填写完整");
    }
  });

  // 清除表单验证
  categoryForm.value.clearValidate();
}

function searchBtn() {
  queryParams.value.pageNum = 1;
  getCourseList();
}

function resetBtn() {
  queryParams.value = {
    courseName: "",
  courseStatus: "",
  courseType: "",
  categoryName: "",
    pageNum: 1,
    pageSize: queryParams.value.pageSize,
  };
  getCourseList();
}

function resetForm() {
  formData.value = {
    courseId: "",
    courseName: "",
  };
  disabled.value = false;
  selected.value = "add";
}

async function getCourseList() {
  try {
    const res = await selectAllCourse(queryParams.value);
    total.value = res.data.course.total;
    tableData.value = res.data.course.records;
    console.log(res.data.course.records);

    for (const item of tableData.value) {
      for (const element of categoryList.value) {
        if (element.categoryId == item.categoryId) {
          item.categoryName = element.categoryName;
        }
      }
    }
  } catch (error) {
    console.log(error);
  }
}

async function getCategoryList() {
  try {
    const res = await selectAllCategory();
    categoryList.value = res.data.categoryList;
    console.log(categoryList.value);
  } catch {
    console.log(e);
  }
}
</script>

<style scoped>
.seckillall {
  height: 100%;
  width: calc(100% - 50px);
  /* background-color: pink; */
  float: left;
}

.head {
  margin-top: 20px;
  margin-left: 20px;
  width: calc(100% - 50px);
}

.middle {
  width: 100%;
  height: 8vh;
  /* background-color: antiquewhite; */
  margin-bottom: 20px;
}

.add {
  margin-top: 15px;
  margin-left: 45px;
  width: 5%;
  height: 50%;
  float: left;
}

.end {
  float: left;
  width: calc(100% - 50px);
}
</style>